#include "ota_http.h"

// http://192.168.56.88:8000/ota_server/gateway_version_info.json

size_t get_text_cb(char *ptr, size_t size, size_t nmemb, void *userdata);

/**
 * @brief 从指定的url获取文本数据
 *
 * @param url
 * @return uint8_t*
 */
uint8_t *ota_http_getText(uint8_t *url)
{
    CURL *curl;
    CURLcode res;

    // 设置全局环境(整个app只需要调用一次)
    curl_global_init(CURL_GLOBAL_DEFAULT);

    // 初始化curl
    curl = curl_easy_init();

    if (curl == NULL)
    {
        log_error("curl_easy_init() failed");
        return NULL;
    }

    // 设置要访问的url地址
    curl_easy_setopt(curl, CURLOPT_URL, url);

    // 设置回调函数, 用来接收网站的相应的数据
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, get_text_cb);

    // 设置回调函数的参数
    uint8_t *buffer = malloc(1024);
    memset(buffer, 0, 1024);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, buffer);

    res = curl_easy_perform(curl); // 阻塞式请求

    if (res != CURLE_OK)
        fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));

    // printf("%s\n", buffer);

    curl_easy_cleanup(curl);

    return buffer;
}

/**
 * @brief 下载文件
 *
 * @param url 文件的url
 * @param file_path 下载的文件保持路径
 */
gate_status_t ota_http_download(uint8_t *url,
                                uint8_t *file_path)
{
    CURL *curl;
    CURLcode res;

    // 设置全局环境(整个app只需要调用一次)
    // curl_global_init(CURL_GLOBAL_DEFAULT);

    // 初始化curl
    curl = curl_easy_init();

    if (curl == NULL)
    {
        log_error("curl_easy_init() failed");
        return ERROR;
    }

    // 设置要访问的url地址
    curl_easy_setopt(curl, CURLOPT_URL, url);

    // 设置回调函数, fwrite: 把收到的数据, 直接调用fwrite写入到文件中
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite);

    // 设置文件名
    FILE *fp = fopen(file_path, "wb"); // 打开文件: wb: 二进制写方式打开
    if (fp == NULL)
    {
        log_error("fopen() failed");
        return ERROR;
    }
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

    res = curl_easy_perform(curl); // 阻塞式请求

    if (res != CURLE_OK)
        fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));

    // printf("%s\n", buffer);
    fclose(fp);
    curl_easy_cleanup(curl);

    return OK;
}

size_t get_text_cb(char *ptr, size_t size, size_t nmemb, void *userdata)
{
    size_t realsize = size * nmemb;
    memcpy(userdata, ptr, realsize);
    ((uint8_t *)userdata)[realsize] = '\0';
    return realsize;
}
